package com.biostime.springdraw.modules.sys.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.springdraw.common.service.CrudService;
import com.biostime.springdraw.common.utils.StringUtils;
import com.biostime.springdraw.modules.sys.dao.UserDao;
import com.biostime.springdraw.modules.sys.entity.User;
import com.biostime.springdraw.modules.sys.entity.UserRole;
import com.biostime.springdraw.modules.sys.utils.UserUtils;

/**
 * 用户表Service
 * @author king
 * @version 2015-11-12
 */
@Service
@Transactional
public class UserService extends CrudService<UserDao, User> {

	public static final String defaultpassword = "0|0|0|0"; //默认显示密码
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Override
	public List<User> findList(User entity) {
		
		dataScopeFilter(entity, "dsf", "id in (select center_id from sys_usercenter where user_id = a.id)", "id=a.create_by");
		
		return super.findList(entity);
	}
	
	public boolean validate(String loginName) {
		return dao.validate(loginName);
	}
	
	@Transactional
	public void saveUser(User user, HttpServletRequest request) {
		String passworld = request.getParameter("password");
		/**用户修改密码**/
		if(!passworld.equals(defaultpassword)){
			user.setPassword(SystemService.entryptPassword(passworld));
		}else{
			user.setPassword(null);
		}
		
		this.save(user);
		
		/**保存用户角色**/
		userRoleService.deleteUserRole(user.getId());
		String[] roles = request.getParameterValues("role");
		if(roles!=null && roles.length>0){
			for(String r : roles){
				UserRole ur = new UserRole();
				ur.setRoleId(StringUtils.toInteger(r));
				ur.setUserId(StringUtils.toInteger(user.getId()));
				userRoleService.save(ur);
			}
		}
				
		// 清除当前用户缓存
		UserUtils.clearCache(user);
		//if (user.getLoginName().equals(user.getLoginName())){
		//	UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		//}
	}

	public void changePwd(User user, String password1,String oldPassword) {
		// TODO Auto-generated method stub
		if(!password1.equals(defaultpassword)){
			user.setPassword(SystemService.entryptPassword(password1));
		}else{
			user.setPassword(oldPassword);
		}
		dao.changePwd(user);
	}
}
